# Copyright 2025 the LlamaFactory team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import TYPE_CHECKING

from transformers.utils import is_flash_attn_2_available, is_torch_sdpa_available

from ...extras import logging
from ...extras.constants import AttentionFunction


if TYPE_CHECKING:
    from transformers import PretrainedConfig

    from ...hparams import ModelArguments


logger = logging.get_logger(__name__)


def configure_attn_implementation(config: "PretrainedConfig", model_args: "ModelArguments") -> None:
    # 如果模型类型是 gemma2，则需要特殊处理注意力实现方式
    if getattr(config, "model_type", None) == "gemma2":
        # 如果用户设置 flash_attn 为 AUTO 或 FA2
        if model_args.flash_attn == AttentionFunction.AUTO or model_args.flash_attn == AttentionFunction.FA2:
            # 检查是否安装了 FlashAttention-2
            if is_flash_attn_2_available():
                # 如果不是 FA2 模式，则强制切换为 FA2 并提示
                if model_args.flash_attn != AttentionFunction.FA2:
                    logger.warning_rank0("Gemma 2 should use flash attention 2, change `flash_attn` to fa2.")
                    model_args.flash_attn = AttentionFunction.FA2
            else:
                # 如果未安装 FA2，则使用 eager 实现并提示
                logger.warning_rank0("FlashAttention-2 is not installed, use eager attention.")
                model_args.flash_attn = AttentionFunction.DISABLED
        # 如果用户指定使用 SDPA，则提示 Gemma-2 不支持 soft-capping
        elif model_args.flash_attn == AttentionFunction.SDPA:
            logger.warning_rank0(
                "Gemma-2 should use soft-capping attention, while the SDPA attention does not support it."
            )

    # 如果当前设置为 AUTO，则不做任何更改
    if model_args.flash_attn == AttentionFunction.AUTO:
        return

    # 如果禁用了 FlashAttention，则使用 eager 实现
    elif model_args.flash_attn == AttentionFunction.DISABLED:
        requested_attn_implementation = "eager"

    # 如果设置为 SDPA，则检查 PyTorch 是否支持 SDPA（需 torch>=2.1.1）
    elif model_args.flash_attn == AttentionFunction.SDPA:
        if not is_torch_sdpa_available():
            logger.warning_rank0("torch>=2.1.1 is required for SDPA attention.")
            return

        requested_attn_implementation = "sdpa"
    # 如果设置为 FA2，则检查是否已安装 FlashAttention-2
    elif model_args.flash_attn == AttentionFunction.FA2:
        if not is_flash_attn_2_available():
            logger.warning_rank0("FlashAttention-2 is not installed.")
            return

        requested_attn_implementation = "flash_attention_2"
    # 遇到未知的 attention 类型则抛出异常
    else:
        raise NotImplementedError(f"Unknown attention type: {model_args.flash_attn}")

    # 如果是 internlm2 模型，使用 attn_implementation 字段配置注意力实现
    if getattr(config, "model_type", None) == "internlm2":  # special case for custom models
        setattr(config, "attn_implementation", requested_attn_implementation)
    # 如果是 kimi_vl 多模态模型，分别配置 vision 和 text 的注意力实现
    elif getattr(config, "model_type", None) == "kimi_vl":
        setattr(config.vision_config, "_attn_implementation", requested_attn_implementation)
        setattr(config.text_config, "_attn_implementation", requested_attn_implementation)
    # 其他情况统一使用 _attn_implementation 字段配置
    else:
        setattr(config, "_attn_implementation", requested_attn_implementation)


def print_attn_implementation(config: "PretrainedConfig") -> None:
    # 如果是 internlm2 模型，读取 attn_implementation 字段
    if getattr(config, "model_type", None) == "internlm2":  # special case for custom models
        attn_implementation = getattr(config, "attn_implementation", None)
    # 其他模型统一读取 _attn_implementation 字段
    else:
        attn_implementation = getattr(config, "_attn_implementation", None)

    # 如果使用了 FlashAttention-2，输出提示信息
    if attn_implementation == "flash_attention_2":
        logger.info_rank0("Using FlashAttention-2 for faster training and inference.")
    # 如果使用了 SDPA，输出提示信息
    elif attn_implementation == "sdpa":
        logger.info_rank0("Using torch SDPA for faster training and inference.")
    # 否则使用默认注意力实现（eager）
    else:
        logger.info_rank0("Using vanilla attention implementation.")
